<template>
    <div>
      <div ref="codeContainer" class="coder-editor"></div>
      <el-button style="position: absolute; right: 18px; top: 0px; z-index:999;" type="text" @click="copyCode" >复制代码</el-button>
    </div>
  </template>
  
  <script>
  import * as monaco from 'monaco-editor';
  export default {
    // https://juejin.cn/post/6984683777343619102
    data() {
      return {
        monacoEditor: null, // 语言编辑器
        oid: '',
      }
    },
    methods: {
      copyCode(){
        document.oncopy = (e) => {
          e.clipboardData.setData("text", this.monacoEditor.getValue());
          e.preventDefault();
          document.oncopy = null;
        };
        document.execCommand("Copy");

        this.$message({
          message: "复制成功",
          type: "success",
        });
      },
      destroy(){
        if(this.monacoEditor){
          this.monacoEditor.dispose();
        }
      },
      init({code, oid, lang}){
        if(this.$refs.codeContainer){
          this.oid = oid;
          // 初始化编辑器，确保dom已经渲染
          this.monacoEditor = monaco.editor.create(this.$refs.codeContainer, {
              value: code, // 编辑器初始显示文字
              language: lang || 'html', // 语言
              automaticLayout: true, // 自动布局
              theme: 'vs-dark', // 官方自带三种主题vs, hc-black, or vs-dark
              minimap: { // 关闭小地图
                enabled: false,
              },
          });

          this.monacoEditor.onDidChangeModelContent((e) => {});

          this.monacoEditor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KEY_S, () => {
              this.$store.commit("CODE_SETTING", { key: this.oid, value: this.monacoEditor.getValue() })
              this.$message.success('保存成功');
          })
        }
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .coder-editor{
    width: 100%;
    height: 570px;
    border: 1px solid rgba(0, 0, 0, 0.08);
  }
  </style>